from iHome.utils.commony import login_required
from flask import current_app,g
from iHome import db, redis_store
import datetime,logging
from flask import request, jsonify
from iHome.models import House, Order
from iHome.utils.response_code import RET
from . import order_blu


@order_blu.route('/order',methods=["POST"])
@login_required
def orders():
    """保存订单"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    """订单添加"""
    data_dict = request.json
    house_id = data_dict.get("house_id")
    start_date_str = data_dict.get("start_date")# 入住时间
    end_date_str = data_dict.get("end_date") # 退房时间

    if not all([house_id,start_date_str,end_date_str]):
        return jsonify(errno=RET.DATAERR , errmsg='参数不为空')

    try:
        start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
        end_date   = datetime.datetime.strptime(end_date_str,"%Y-%m-%d")
        assert start_date < end_date, Exception('开始日期大于结束日期')
        # 计算出入住天数
        days = (end_date - start_date).days
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        # 查询房屋是否存在
        house = House.query.get(house_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    try:
        # 判断是否有人入住
        filters = [Order.house_id == house_id,Order.begin_date < start_date,Order.end_date>end_date]
        count = Order.query.filter(*filters).count()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.NODATA, errmsg='参数错误')

    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg='已被预约')

    amount = days * house.price
    # 数据添加
    order = Order()
    order.user_id = user.id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = amount
    order.house_id = house_id


    try:
        # 订单信息添加
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据添加失败')

    return jsonify(errno=RET.OK, errmsg='为你展示中',data={"order_id": order.id})


#-------------------------------------------------------------------------
#获取用户订单列表（房主+客户）
@order_blu.route("/orders")
@login_required
def display_order():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = g.user_id
    #获取参数，判断是客户还是房主
    role=request.args.get("role")
    #客户
    if role=="custom":
        #数据库查询获取订单对象
        order_list=[]
        try:
            order_list=Order.query.filter(Order.user_id==user_id).order_by(Order.create_time.desc())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="订单获取失败")
    else:
        # 查询自己房屋都有哪些订单
        houses = House.query.filter_by(user_id=user_id).all()
        house_ids = [house.id for house in houses]
        order_list = Order.query.filter(Order.house_id.in_(house_ids)).order_by(Order.create_time.desc())

    orders_dict = []

    for order in order_list:
        orders_dict.append(order.to_dict())

    return jsonify(errno=RET.OK, errmsg="请求成功", data={"orders": orders_dict})
#-----------------------------------------------------------------------------------------------------

# 房主接单及拒单
@order_blu.route("/orders",methods=["PUT"])
@login_required
def orders_action():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    #获取参数
    data_dict=request.json
    order_id=data_dict.get("order_id")
    action=data_dict.get("action")
    reason=data_dict.get("reason")

    #判空，检验
    if not all([order_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    if action not in ("accept","reject"):
        return jsonify(errno=RET.PARAMERR,errmsg="参数有误")

    if action=="reject" and not reason:
        return jsonify(errno=RET.PARAMERR,errmsg="请填写拒单原因")
    # 数据库中获取订单对象

    order = Order.query.get(order_id)

    #根据action判断操作
    if action=="accept":
        #修改订单状态为“待评价”，并返回数据库
        order.status="WAIT_COMMENT"
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="接单失败，稍后再试")
        return jsonify(errno=RET.OK,errmsg="接单成功")

    # 修改订单状态为“拒绝”，并返回数据库
    order.status = "REJECTED"
    order.comment=reason
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="接单失败，稍后再试")

    return jsonify(errno=RET.OK, errmsg="拒单成功")
#-----------------------------------------------------------------------------------------------------


#评论订单
@order_blu.route("/orders/comment",methods=["PUT"])
@login_required
def orders_comment():

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    #获取参数
    data_dict=request.json
    order_id=data_dict.get("order_id")
    comment=data_dict.get("comment")

    #判空
    if not all([order_id,comment]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    # 通过订单id查询出订单模型
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_COMMENT").first()
        house = order.house
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')

    #添加评论
    house.order_count += 1
    order.comment=comment
    order.status="COMPLETE"

    #上传数据库
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据上传失败")

    # 删除redis中缓存的房屋详情信息,因为房屋详情信息已经更新
    try:
        redis_store.delete('house_info_' + house.id)
    except Exception as e:
        logging.error(e)

    return jsonify(errno=RET.OK,errmsg="评论成功")
